package com.blueskykong.tm.mq;

import com.blueskykong.tm.common.holder.LogUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;

/**
 * @Author: JasonChen86899
 */
public abstract class TxMQManager<T extends TxMQClient> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TxMQManager.class);

    private final List<T> clients = Lists.newArrayList();


    /**
     * 加载 MQ 驱动实例类
     */
    protected void loadInital(Class<T> t) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                ServiceLoader<T> loaderServices = ServiceLoader.load(t);
                for (T loaderService : loaderServices) {
                    LogUtil.debug(LOGGER, "加载 MQ 驱动：{}", () -> loaderService.getClass().getName());
                    clients.add(loaderService);
                }
                return null;
            }
        });
    }

    /**
     * 借鉴jdbc获取连接方式，此处获取非空的连接对象及表示连接成功
     *
     * @return
     */
    public T getMQClient() {
        for (T client : clients) {
            if (Objects.nonNull(client.getInstance()))
                return client;
        }
        return null;
    }
}
